class Base32Code:
    Base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"

    @staticmethod
    def encode(data):
        result = []
        buffer = data[0]
        next_index = 1
        bits_left = 8
        while bits_left > 0 or next_index < len(data):
            if bits_left < 5:
                if next_index < len(data):
                    buffer <<= 8
                    buffer |= data[next_index] & 0xFF
                    next_index += 1
                    bits_left += 8
                else:
                    pad = 5 - bits_left
                    buffer <<= pad
                    bits_left += pad
            index = 0x1F & (buffer >> (bits_left - 5))
            bits_left -= 5
            result.append(Base32Code.Base32Chars[index])
        return "".join(result)

    @staticmethod
    def decode(base32):
        base32 = base32.rstrip("=")  # Remove padding characters
        byte_count = len(base32) * 5 // 8  # This must be TRUNCATED
        return_array = bytearray(byte_count)
        buffer = 0
        bits_in_buffer = 0
        array_index = 0

        for c in base32:
            c_value = Base32Code.Base32Chars.index(c.upper())
            if c_value < 0:
                raise ValueError("Invalid character in base32 string")

            buffer = (buffer << 5) | c_value
            bits_in_buffer += 5

            if bits_in_buffer >= 8:
                return_array[array_index] = buffer >> (bits_in_buffer - 8)
                array_index += 1
                bits_in_buffer -= 8
                buffer &= (1 << bits_in_buffer) - 1

        return return_array
